package com.zlfund.cat.zjgsmk.util;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.zlfund.cat.zjgsmk.adapter.ViewpagerAdapter;
import com.zlfund.cat.zjgsmk.net.RxNetErrorEmptyImp;
import com.zlfund.cat.zjgsmk.util.timetask.TimerService;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * Created by chenj
 * Created on 2017/8/18
 */

public class ViewpagerHelper implements View.OnTouchListener {
    private ViewPager mViewPager;
    private ViewpagerAdapter mPagerAdapter;
    private List<String> mList;
    private boolean mViewpagerIdle;     //广告图是否在滑动
    private TimerService mService;
    private boolean mIsAutoRoll;
    private View mLeftView,mRightView;
    private List<View> mViews;

    public ViewpagerHelper(ViewPager viewPager) {
        mViewPager = viewPager;
        mViewPager.setOnTouchListener(this);
        setMultiPageInOneScreen();
        mViews = new ArrayList<>();
    }

    public void addOnLeftAndRightTouchListener(View leftView, View rightView) {
        if (leftView != null) leftView.setOnTouchListener(this);
        if (rightView != null) rightView.setOnTouchListener(this);
        mLeftView = leftView;
        mRightView = rightView;
    }

    public void setList(Context context, List<String> list) {
        mList = list;
        if (mList == null || mList.size() == 0) return;
        mViews.clear();
        if (mList.size() >= 2) {
            mViews.add(createImageView(context, mList.get(mList.size() - 2)));
            mViews.add(createImageView(context, mList.get(mList.size() - 1)));
            for (String imgUrl : mList) {
                mViews.add(createImageView(context, imgUrl));
            }
            mViews.add(createImageView(context, mList.get(0)));
            mViews.add(createImageView(context, mList.get(1)));
        }else {
            mViews.add(createImageView(context,mList.get(0)));
        }
        mPagerAdapter.setList(mViews);
        if (mList.size() > 1)
            mViewPager.setCurrentItem((int) Math.ceil(mList.size() * 1.0f / 2f));
        startAutoRoll();
    }

    private ImageView createImageView(Context context, String url) {
        ImageView iv = new ImageView(context);
        iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        GlideUtil.loadUrl(context, url, iv);
        return iv;
    }

    public void startAutoRoll() {
        if (mIsAutoRoll) return;
        mIsAutoRoll = true;
        mService = new TimerService();
        Observable<Long> observable = Observable.create(new ObservableOnSubscribe<Long>() {
            @Override
            public void subscribe(@NonNull final ObservableEmitter<Long> e) throws Exception {
                mService.timeSchedule(new Runnable() {
                    @Override
                    public void run() {
                        e.onNext(mService.getTotalTime());
                    }
                }, 3000, 3000);
            }
        });
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aVoid) throws Exception {
                        mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                    }
                },new RxNetErrorEmptyImp());
    }

    public boolean isRunning() {
        return mService != null && mService.isRunning();
    }

    public void stopAutoRoll() {
        if (!mIsAutoRoll) return;
        mIsAutoRoll = false;
        if (mService == null) return;
        mService.cancel();
    }

    private void setMultiPageInOneScreen() {
        mPagerAdapter = new ViewpagerAdapter(null);
        mViewPager.setPageMargin(20);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setPageTransformer(true, new ScaleTransformer());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            private int mPosition;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                mViewpagerIdle = state == ViewPager.SCROLL_STATE_IDLE;
                if (mPosition == 1) {
                    mViewPager.setCurrentItem(mViews.size() - 3, false);
                } else if (mPosition == mViews.size() - 2) {
                    mViewPager.setCurrentItem(2, false);
                }
            }
        });
    }

    private float mLeftPreX = 0;
    private float mRightPreX = 0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v == mViewPager) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                stopAutoRoll();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                startAutoRoll();
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                startAutoRoll();
            }
            return false;
        }
        if (!mViewpagerIdle) return true;
        if (mList == null || mList.size() == 0) return true;
        boolean hasMove = false;
        float curX = event.getX();
        if (mLeftView.getId() == v.getId()) {
            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                if (Math.abs(curX - mLeftPreX) > ViewConfiguration.get(v.getContext()).getScaledTouchSlop()) {
                    hasMove = true;
                }
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (hasMove && mLeftPreX > curX)
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                else
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
            }
            mLeftPreX = event.getX();
        }else if (mRightView.getId() == v.getId()) {
            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                if (Math.abs(curX - mRightPreX) > ViewConfiguration.get(v.getContext()).getScaledTouchSlop()) {
                    hasMove = true;
                }
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (hasMove && mRightPreX < curX)
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
                else
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
            }
            mRightPreX = event.getX();
        }
        return true;
    }
}
